/*
 * yuechao
 * 
 * 依赖于 conf.js,utils.js,jquery.js
 */
$.ajaxSetup({ url: ServerEnvironment.remoteUrl + "/main.handler" });
var proxyCache = new utils.Dictionary();

/**
 * var proxy = jQuery.useService(proxyName);
 */
jQuery.extend({
    ajaxProxy: function(remoteSettings) {
        var request = {
    		"headers": {
    			"sessionId": "",
                "clazzName": remoteSettings.clazzName,
                "methodName": remoteSettings.methodName,
                "apiVersion": "1.0", // must be 1.0
                "dataFormat": "json"
    		},
            "arguments": remoteSettings.parameters
        };

        request = utils.toJSONString(request);

        var origSettings = {
            type: "POST",
            contentType: "application/text;charset=utf-8",
            dataType: "text",
            timeout: remoteSettings.timeout,
            async: remoteSettings.async,
            data: request,
            beforeSend: remoteSettings.beforeSend,
            success: function(data, status, xhr) {
                if (remoteSettings.success) {
                    var json = $.parseJSON(data);
                    if (json.isDone) {
                    	var content = $.parseJSON(json.content);
                        remoteSettings.success(content, status, xhr, json.headers.who);
                    } else if (remoteSettings.error) {
                        remoteSettings.error(xhr, "error", json.content);
                    }
                }
            },
            complete: remoteSettings.complete,
            error: remoteSettings.error
        };

        return $.ajax(origSettings);
    },

    useService: function(clazzName, methodNames) {
        if (proxyCache.containsKey(clazzName)) {
            return proxyCache.item(clazzName);
        }

        var objectName = "$Proxy$" + clazzName.replace(/\./g, '_');
        var sEval = objectName + " = {};";
        for (var i = 0; i < methodNames.length; i++) {
            var methodName = methodNames[i];
            sEval += objectName + "." + methodName + " = function() {" +
                 "var args = utils.toProxyArray(arguments);" +
                 "var settings = args.pop();" +
                 "$.ajaxProxy({" +
                    "clazzName: \"" + clazzName + "\", " +
                    "methodName: \"" + methodName + "\", " +
                    "parameters: args, " +
                    "beforeSend: settings.beforeSend, " +
                    "complete: settings.complete, " +
                    "error: settings.error, " +
                    "success: settings.success" +
                 "});" +
            "};";
        }

        sEval += objectName + ";";
        var proxy = eval(sEval);
        proxyCache.add(clazzName, proxy);

        return proxy;
    }
});